/*
              图形id     视频id    解码显示id
 barcode.init('canvas', 'video', 'codeInfo');
*/
barcode = {
    ScanCanvas: null,
    ScanContext: null,
    mediaStreamTrack: null,
    video: null,
    constraints: {
        audio: false,
        video: {
            width: 720,
            height: 720
        }
    },
    mode: 'environment',//默认后置摄像头
    init: function (canvasid, videoid, textid) {
        barcode.ScanCanvas = barcode.FixCanvas(document.getElementById(canvasid));
        barcode.ScanCanvas.width = 640;
        barcode.ScanCanvas.height = 480;
        barcode.ScanContext = barcode.ScanCanvas.getContext("2d");
        barcode.video = document.getElementById(videoid);

        // // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
        if (navigator.mediaDevices === undefined) {
            navigator.mediaDevices = {};
        }

        navigator.mediaDevices.getUserMedia(barcode.constraints)
            .then(function (stream) {
                // 旧的浏览器可能没有srcObject
                if ("srcObject" in barcode.video) {
                    barcode.video.srcObject = stream;
                } else {
                    //避免在新的浏览器中使用它，因为它正在被弃用。
                    barcode.video.src = window.URL.createObjectURL(stream);
                }
                barcode.video.onloadedmetadata = function (e) {
                    barcode.video.play();
                };
            })
            .catch(function (err) {
                console.log(err.name + ": " + err.message);
            });

        //直接调用方法，实现页面加载完就自动打开摄像头
        barcode.takePhoto();
        BarcodeReader.Init();
        BarcodeReader.SetImageCallback(function (result) {
            if (!result.length) {
                document.getElementById(textid).value = '条形码读取失败';
                return
            }
            var barcodeinfo = result[0];
            if (barcodeinfo.Value) {
                document.getElementById(textid).value = '条形码信息是：' + barcodeinfo.Value;
            }
            //console.log("1.===" + barcode.Value);
        });
    },
    success: function (stream) {
        //兼容webkit核心浏览器
        let CompatibleURL = window.URL || window.webkitURL;
        //将视频流设置为video元素的源
        barcode.mediaStreamTrack = stream.getTracks()[0];

        //console.log('mediaStreamTrack', barcode.mediaStreamTrack)
        barcode.video.srcObject = stream;
        barcode.video.play();

        //console.log('video', barcode.video)
    },
    error: function (error) {
        alert('访问用户媒体设备失败,请尝试更换浏览器')
    },
    //请求摄像头
    takePhoto: function () {
        if (navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia ||
            navigator.mozGetUserMedia) {
            alert(barcode.mode);
            //调用用户媒体设备, 访问摄像头
            barcode.getUserMedia({
                video: {
                    width: 720,
                    height: 720,
                    facingMode: barcode.mode //设置使用后置摄像头，user为前置摄像头
                }
            }, barcode.success, barcode.error);
        } else {
            alert('不支持访问用户媒体');
        }
    },
    //切换摄像头
    changeMode: function () {
        barcode.mode = barcode.mode === 'user' ? 'environment' : 'user';
        barcode.mediaStreamTrack.stop();
        barcode.takePhoto();
    },
    //解码
    mydecode: function (canvasid) {
        //var date = new Date().getTime();
        // 点击，canvas画图
        barcode.ScanContext.drawImage(barcode.video, 0, 0, 300, 300);
        // 获取图片base64链接
        var image = barcode.ScanCanvas.toDataURL('image/png');
        // 定义一个img
        var img = new Image();
        //设置属性和src
        img.id = "imgBox";
        img.src = image;
        img.style = "display:none"
        //因此图片
        var canvas = document.getElementById(canvasid);
        canvas.style = "display:none"
        //解析条码
        BarcodeReader.DecodeImage(img);
    },
    // base64转文件
    dataURLtoFile: function (dataurl, filename) {
        var arr = dataurl.split(','),
            mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]),
            n = bstr.length,
            u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, {
            type: mime
        });
    },
    //访问用户媒体设备的兼容方法
    getUserMedia: function (constraints, success, error) {
        //console.log('constraints', constraints)
        //console.log('success', success)
        //console.log('error', error)
        if (navigator.mediaDevices.getUserMedia) {
            //最新的标准API
            navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error);
        } else if (navigator.webkitGetUserMedia) {
            //webkit核心浏览器
            navigator.webkitGetUserMedia(constraints, success, error)
        } else if (navigator.mozGetUserMedia) {
            //firfox浏览器
            navigator.mozGetUserMedia(constraints, success, error);
        } else if (navigator.getUserMedia) {
            //旧版API
            navigator.getUserMedia(constraints, success, error);
        }
    },
    FixCanvas: function (canvas) {
        var ctx = canvas.getContext('2d');
        var drawImage = ctx.drawImage;
        ctx.drawImage = function (img, sx, sy, sw, sh, dx, dy, dw, dh) {
            var vertSquashRatio = 1;
            if (!!img && img.nodeName === 'IMG') {
                vertSquashRatio = BarcodeReader.DetectVerticalSquash(img);
                // sw || (sw = img.naturalWidth);
                // sh || (sh = img.naturalHeight);
            }
            if (arguments.length === 9)
                drawImage.call(ctx, img, sx, sy, sw, sh, dx, dy, dw, dh / vertSquashRatio);
            else if (typeof sw !== 'undefined')
                drawImage.call(ctx, img, sx, sy, sw, sh / vertSquashRatio);
            else
                drawImage.call(ctx, img, sx, sy);
        };
        return canvas;
    }
}